package cn.gaozhong.basic.controller;


import cn.gaozhong.basic.exception.CustomException;
import cn.gaozhong.basic.util.AjaxResult;
import cn.gaozhong.basic.util.FastdfsUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/fastDfs")
public class FastDfsController {


    @PostMapping("/upload")
    public AjaxResult upload(@RequestPart(value = "file",required = true) MultipartFile file){
        try {
            String filename = file.getOriginalFilename();
            String extName = filename.substring(filename.lastIndexOf(".") + 1);
            String path = FastdfsUtil.upload(file.getBytes(), extName);
            return new AjaxResult().setResultObj(path);
        } catch (CustomException e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("系统繁忙，请稍后重试");
        }

    }
    @DeleteMapping
    public AjaxResult delete(@RequestParam String path) {
        //   /group1/M00/00/05/CgAIC2Kl9USAMiloAAEET8BgGF8931.jpg
        try {
            //  group1/M00/00/05/CgAIC2Kl9USAMiloAAEET8BgGF8931.jpg
            String pathTmp = path.substring(1);
            //  group1
            String group = pathTmp.substring(0, pathTmp.indexOf("/"));
            //  M00/00/05/CgAIC2Kl9USAMiloAAEET8BgGF8931.jpg
            String filename = pathTmp.substring(pathTmp.indexOf("/") + 1);
            FastdfsUtil.delete(group,filename);
            return new AjaxResult();
        }catch (CustomException e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("系统繁忙，请稍后重试");
        }
    }
}
